#!/usr/bin/env python3
"""
从日志文件中提取查询
提取格式为 current query : (...) 或 current query : [...] 的行
但如果下一行是 found in sqlite : ['NoResponse', 'None'] 这种格式，则不提取
"""

import re

def extract_queries(log_file, output_file):
    """
    从日志文件中提取查询
    
    Args:
        log_file: 输入日志文件路径
        output_file: 输出文件路径
    """
    queries = []
    
    with open(log_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        
        # 匹配 current query 行
        match = re.search(r'current query\s*:\s*(.+)', line)
        if match:
            query_str = match.group(1).strip()
            
            # 检查下一行是否是 found in sqlite
            if i + 1 < len(lines):
                next_line = lines[i + 1].strip()
                sqlite_match = re.search(r'found in sqlite\s*:\s*(.+)', next_line)
                
                if sqlite_match:
                    sqlite_result = sqlite_match.group(1).strip()
                    # 如果结果是 ['NoResponse', 'None'] 或 ['None', 'NoResponse']，跳过
                    # 精确匹配这两种格式
                    if sqlite_result == "['NoResponse', 'None']" or sqlite_result == "['None', 'NoResponse']":
                        i += 2
                        continue
            
            # 提取查询（可能是元组或列表格式）
            queries.append(query_str)
        
        i += 1
    
    # 保存到文件
    with open(output_file, 'w', encoding='utf-8') as f:
        for query in queries:
            f.write(query + '\n')
    
    print(f"提取了 {len(queries)} 个查询")
    print(f"结果已保存到: {output_file}")
    
    # 打印前10个查询作为示例
    print("\n前10个查询示例:")
    for i, query in enumerate(queries[:10], 1):
        print(f"{i}. {query}")
    
    return queries

if __name__ == '__main__':
    log_file = '1.log'
    output_file = 'extracted_queries.txt'
    
    queries = extract_queries(log_file, output_file)

